import { OrganizationItem } from 'admin/schema/Cas';
import store from '../../../../store';
import { JSONObject } from '../../../schema/common';
import { UploadFile } from 'antd/es/upload/interface';
import { map } from 'lodash';

export const convertToTree = (
  data: Omit<OrganizationItem, 'children' | 'description'>[],
  options = {
    idKey: 'id',
    parentKey: 'pid',
    childrenKey: 'children',
    rootId: '0',
  }
) => {
  // 合并配置参数
  const { idKey = 'id', parentKey = 'pid', childrenKey = 'children', rootId = '0' } = options;

  // 创建哈希映射表并初始化子节点数组
  const nodeMap = new Map();
  const rootNodes = [];

  // 第一轮遍历：创建所有节点副本并建立索引
  for (const item of data) {
    const node = {
      ...item,
      [childrenKey]: [], // 初始化子节点，避免undefined
    };
    nodeMap.set(node[idKey], node);
  }

  // 第二轮遍历：构建父子关系
  for (const node of nodeMap.values()) {
    const parentId = node[parentKey];

    // 根节点直接加入结果集
    if (parentId === rootId) {
      rootNodes.push(node);
      continue;
    }

    // 查找父节点并建立关联
    const parent = nodeMap.get(parentId);
    if (parent) {
      parent[childrenKey].push(node);
    } else {
      // 处理孤儿节点：提升为根节点
      console.warn(`Orphan node detected: ${node[idKey]} (parent ${parentId} not found)`);
      rootNodes.push(node);
    }
  }

  return rootNodes;
};

export const downLoadByUrl = (url: string, filename: string) => {
  const encryptToken = (store.getState() as JSONObject).encryptToken;
  const userId = (store.getState() as JSONObject)?.loginInfo?.id;

  let xhr = new XMLHttpRequest();
  //GET请求,请求路径url,async(是否异步)
  xhr.open('GET', url, true);
  //设置请求头参数的方式,如果没有可忽略此行代码
  xhr.setRequestHeader('userId', userId || '');
  xhr.setRequestHeader('uniqueToken', encryptToken || '');
  //设置响应类型为 blob
  xhr.responseType = 'blob';
  //关键部分
  xhr.onload = function () {
    //如果请求执行成功
    if (this.status === 200) {
      let blob = this.response;
      let a = document.createElement('a');

      //创键临时url对象
      let url = URL.createObjectURL(blob);

      a.href = url;
      a.download = filename;
      a.click();
      //释放之前创建的URL对象
      window.URL.revokeObjectURL(url);
    }
  };
  //发送请求
  xhr.send();
};

// 获取文件预览列表
export const getFileList = (fileValue: string): UploadFile[] => {
  if (!fileValue) return [];

  try {
    const fileData = JSON.parse(fileValue);
    if (Array.isArray(fileData)) {
      return map(fileData, (file: any) => ({
        uid: file.id || '-1',
        name: file.realName || file.name,
        status: 'done',
        response: {
          status: 200,
          data: [file],
        },
      }));
    }
  } catch (error) {
    console.error('解析文件数据失败:', error);
  }
  return [];
};
